let fs = require('fs');
let path = require('path');
var sqlite3 = require('sqlite3');

class DbUtil {
    constructor(dbPath, emptyDbFile) {
        if (!fs.existsSync(dbPath)) {
            console.log("Copying Db ...");
            fs.mkdirSync(dbPath);
        }
        dbPath = path.join(dbPath, "converter.db");
        if (!fs.existsSync(dbPath)) {
            console.log("Copying Db ...");
            fs.createReadStream(emptyDbFile).pipe(fs.createWriteStream(dbPath));
        }
        this.db = new sqlite3.Database(dbPath);
        console.log("DB init Success !")
    }

    getRecords(sql, cb) {
        this.all(sql, cb)
    }

    async insertUpdateHis(db, data,cb) {
        let uniqid = data['uniqid'];
        let id = await this.getIdByUniqId(db,uniqid);
        let sql = "";
        if (id) {
            delete data['uniqid'];
            sql = "UPDATE " + db + " SET " + this.generateUpdateSql(data) + " WHERE uniqid = '" + uniqid + "'";
        } else {
            sql = "insert into " + db + this.generateInsertSql(data);
        }
        this.run(sql,cb);
    }

    deleteHis(db, id) {
        let sql = "";
        if (id) {
            sql = "DELETE FROM " + db + " WHERE id = '" + id + "'";
        }
        this.run(sql);
    }

    checkCount(db,cb) {
        let sql = "SELECT " +
            "count(id) as doing_count " +
            "FROM "+db+" where status = 0";
        this.get(sql,cb)
    }

    async test() {

    }

    async getIdByUniqId(db,uniqid) {
        let sql = "select id from "+db+" where uniqid = '" + uniqid + "'";
        return new Promise(resolve => {
            this.get(sql, function (err, row) {
                if (!err && row) {
                    resolve(row.id);
                }
                resolve(0)
            });
        });
    }

    generateInsertSql(data) {
        let keys = Object.keys(data);

        let temp_k = [];
        let temp_v = [];
        for (let i = 0; i < keys.length; i++) {
            let k = keys[i];
            let val = data[k];

            temp_k.push("'" + k + "'");
            temp_v.push("'" + val + "'");
        }
        return "(" + temp_k.join(",") + ") VALUES (" + temp_v.join(",") + ")";
    }

    generateUpdateSql(data) {
        let keys = Object.keys(data);

        let where = [];
        for (let i = 0; i < keys.length; i++) {
            let k = keys[i];
            let val = data[k];

            where.push("'" + k + "' = " + "'" + val + "'");
        }
        return where.join(",");
    }

    run(sql, cb) {
        try {
            this.db.run(sql, cb);
        } catch (e) {
            console.log(e)
        }
    }

    get(sql, cb) {
        try {
            this.db.get(sql, cb);
        } catch (e) {
            console.log(e)
        }
    }

    all(sql, cb) {
        try {
            this.db.all(sql, cb);
        } catch (e) {
            console.log(e)
        }
    }
}

module.exports = DbUtil;